//
//  IMMessageViewController.m
//  TQY
//
//  Created by 甘世清 on 2024/10/18.
//

#import "IMMessageViewController.h"
#import "BaseMessageTableViewCell.h"
#import "IMMessageManager.h"
#import "MateReportPopView.h"
#import "ImageMessageTableViewCell.h"
@interface IMMessageViewController ()<UITableViewDelegate,UITableViewDataSource,QExtendBoardViewDelegate,QEmotionBoardViewDelegate>
@property (nonatomic , strong)PeopleModel * model;

 
@end

@implementation IMMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.zx_navTitle = self.listModel.toUserName;
    WS(weakSelf);
    [self zx_setRightBtnWithImg:SQGetImage(@"gengduo") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [weakSelf SQ_reportButtonClick];
    }];
    [self SQ_tableViewAddRefresh];
   
    [self SQ_HeaderView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(SQ_DataForModel:) name:@"IMMessageModel" object:nil];
    
   
}
- (void)SQ_viewWillAppear:(BOOL)animated{
    if (self.jsonArray.count<=0) {
        [self SQ_Header];
    } 
}
- (void)SQ_Header{
    NSArray * personArr = [TQYFMDBManager SQ_UserAcquireID:self.listModel.roomId size:self.listModel.messageCount+20 page:self.jsonArray.count];
    if (personArr.count > 0) {
        self.page += 1;
        for (IMMessageModel * model in personArr) {
            [self.jsonArray insertObject:model atIndex:0];
        }
        [self.tableView reloadData];
        if (self.jsonArray.count > personArr.count) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.jsonArray.count - personArr.count inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
    }else{
        [self.tableView reloadData];
    }
    //设置全部已读
    //打开就清空聊天未读数
    BOOL  isok  = [TQYFMDBManager SQ_updateModel:self.listModel.roomId];
    if (isok) {
        self.listModel.messageCount = 0;
    }
    [self.tableView.mj_header endRefreshing];
    [self SQ_reloadMessageCount];
}
//来消息了
-(void)SQ_DataForModel:(NSNotification*)notification{
    IMMessageModel * model = [IMMessageModel mj_objectWithKeyValues:notification.object];
  if ([self.model.userid isEqualToString:model.toUser]) {
      model.toUserPortrait = self.model.portrait;
      [self.jsonArray addObject:model];
      [self insertAndScrollToBottom:model needClearInputText:NO];
      //清空聊天未读数
      [TQYFMDBManager SQ_updateModel:self.listModel.roomId];
  }
    [self SQ_reloadMessageCount];
}

//点击了系统键盘的发送按钮 //文字消息
- (void)inputBarView:(QInputBarView *)inputBarView onKeyboardSendClick:(NSString *)inputNormalText {
    if (![inputNormalText isNotEmpty]) {
        [YJProgressHUD showMsgWithoutView:@"聊天内容不能为空"];
        return;
    }
    //获取模型
    IMMessageModel * model = [[IMSendMessageManager sharedIMManager] SQ_sendTextMessage:inputNormalText info:self.model];
    model.toUser = self.listModel.toUser;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:YES];
  
}
//图片消息
-(void)SQ_getImage:(UIImage *)image{
    IMMessageModel * model = [[IMSendMessageManager sharedIMManager] SQ_sendImageMessage:image info:self.model];
    model.toUser = self.listModel.toUser;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:NO];
    
}
//定位消息
- (void)SQ_sendLoaction:(NSMutableDictionary *)dic{
    IMMessageModel * model = [[IMSendMessageManager sharedIMManager] SQ_sendLocationMessage:dic info:self.model];
    model.toUser = self.listModel.toUser;
    [self.jsonArray addObject:model];
    [self insertAndScrollToBottom:model needClearInputText:NO];
}

 //用户基本信息
- (void)SQ_HeaderView{
    if (self.model !=nil) {
        return;
    }
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.listModel.toUser forKey:@"uid"];
    [HttpTool post:@"user/userInfo" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        self.model = [PeopleModel mj_objectWithKeyValues:httpModel.data];
        self.listModel.toUserPortrait = self.model.portrait;
        self.listModel.toUserName = self.model.name;
        self.zx_navTitle = self.model.name;
        [self.tableView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
    //已读消息
    NSMutableDictionary * data = [[NSMutableDictionary alloc]init];
    [data setObject:self.listModel.toUser forKey:@"friendId"];
    [HttpTool post:@"im/message/private/readed" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        self.model = [PeopleModel mj_objectWithKeyValues:httpModel.data];
        self.zx_navTitle = self.model.name;
        [self.tableView reloadData];
      
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.jsonArray.count;
}
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    IMMessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (self.model) {
        model.toUserName = self.model.name;
        model.toUserPortrait = self.model.portrait;
    }  
    BaseMessageTableViewCell * cell = [IMMessageManager SQ_createMessageCellForMessageModel:model array:self.jsonArray index:indexPath.item tableview:tableView];
    WS(weakSelf);
    [cell setSQ_menuTouchActionBlock:^(NSString * _Nonnull type) {
        [weakSelf SQ_cellButtonClick:model type:type index:indexPath];
    }];
    [cell.reloadBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        model.needToSend = @"需要发送";
        [weakSelf.tableView reloadData];
    }];
    return cell;
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    IMMessageModel * model = [self.jsonArray objectAtIndex:indexPath.item];
   return  [IMMessageManager SQ_getCellHeightMessageModel:model indexPath:indexPath tableview:tableView];
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.keyBoardManager hideAllBoardView];
}
//cell上的各种点击事件
-(void)SQ_cellButtonClick:(IMMessageModel*)model type:(NSString*)type index:(NSIndexPath*)indexPath{
    if ([type isEqualToString:@"查看图片"]) {
        NSInteger index = 0;
        NSMutableArray * imageArray = [[NSMutableArray alloc]init];
        for (IMMessageModel * models in self.jsonArray) {
            if ([models.messType isEqualToString:@"img"]) {
                if (![models.content isNotEmpty]) {
                    break;
                } 
                ImageMessageTableViewCell * cell = (ImageMessageTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
                YBIBImageData * data = [YBIBImageData new];
                data.imageURL = SQURLImage(models.content);
                data.projectiveView = cell.showImage;
                [imageArray addObject:data];
                if ([model.content isEqualToString:models.content]) {
                    index = imageArray.count - 1;
                }
            }
        }
        YBImageBrowser * brow = [YBImageBrowser new];
        brow.dataSourceArray = imageArray;
        brow.currentPage = index;
        [brow show];
    }else if ([type isEqualToString:@"更新会话"]){
        if ([model.needToSend isEqualToString:@"发送失败"]) {
            if (![model.pid isNotEmpty]) {
                model.pid = [TQYFMDBManager SQ_getpid];
            }
            [self.tableView reloadData];
        }
        [TQYFMDBManager SQ_addListIMMessage:model];
        self.listModel.content = model.content;
        self.listModel.type = model.type;
        self.listModel.sendTime = model.sendTime;
        [TQYFMDBManager SQ_addListModel:self.listModel];
       
    }else if ([type isEqualToString:@"删除本地"]){
        [TQYFMDBManager SQ_deletetMessage:model]; //删除本地
        [self.jsonArray removeObject:model];//删除列表
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];//刷新列表
        self.listModel.content = @"";
        self.listModel.sendTime = [NSString SQ_currentTime];
        if (self.jsonArray.count > 0) {
            IMMessageModel * mo = [IMMessageModel new];
            mo = [self.jsonArray lastObject];
            self.listModel.content = mo.content;
            self.listModel.sendTime = mo.sendTime;
        }
        [TQYFMDBManager SQ_addListModel:self.listModel];
    }else if ([type isEqualToString:@"点击头像"]){
        NSArray * controllers = self.navigationController.viewControllers;
        BOOL isFromPeople = NO;
        for (BaseViewController * vc in controllers) {
            if ( [vc isKindOfClass:[PeopleDetailViewController class]]) {
                isFromPeople = YES;
            }
        }
        if (isFromPeople) {
            [self SQ_popViewVC];
        } else {
            PeopleDetailViewController * vc = [PeopleDetailViewController alloc];
            vc.uid = self.listModel.toUser;
            [self SQ_pushViewControllerFull:vc];
        }
    }
}

-(void)SQ_reportButtonClick{
    MateReportPopView * vc = [[MateReportPopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, 260+FootHeight)];
    MateModel * model = [MateModel new];
    model.uid = self.listModel.toUser; 
    vc.model = model;
    vc.type  = @"1";
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                             parentView:nil
                                               popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleBottom;
  
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
    [vc.moreBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
    }];
    WS(weakSelf);
    [vc setHideMatetouchBlock:^{
        [wk_pop dismiss];
        [weakSelf SQ_popViewVC];
    }];
}
 
 
- (void)dealloc{
    DTLog(@"当前AI聊天im类是否释放");
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.keyBoardManager.viewControllerWillDisappear = NO;
}
 
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 避免手势返回的时候输入框往下掉
    self.keyBoardManager.viewControllerWillDisappear = YES;
}
@end
